Stored Procedures [dbo].[asi_CreateRebuildOrRenamePK]
Properties
PropertyValue
ANSI Nulls OnYes
Quoted Identifier OnYes
Parameters
NameData TypeMax Length (Bytes)
@tablenamenvarchar(512)1024
@columnsnvarchar(512)1024
SQL Script
CREATE PROCEDURE [dbo].[asi_CreateRebuildOrRenamePK]
    @tablename nvarchar(512),
    @columns nvarchar(512)
AS
BEGIN
    DECLARE @keyName nvarchar(512)
    DECLARE @indexname nvarchar(512)

    -- get the name of the table's Primary Key
    SELECT @keyName = name
      FROM sysobjects
     WHERE parent_obj = OBJECT_ID(@tablename)
       AND xtype = 'PK'

    SET @indexname = 'PK_' + @tablename

    -- if the key exists...
    IF @keyName IS NOT NULL
    BEGIN
        IF @keyName <> ('PK_' + @tablename)
        BEGIN
            -- if it not named according to our conventions, rename it
            EXEC ('sp_rename ''' + @keyName + ''', ''' + @indexname + ''', ''OBJECT''')
        END
        ELSE
        BEGIN
            -- otherwise rebuild it
            DBCC DBREINDEX (@tablename, @indexname) WITH NO_INFOMSGS
        END
    END

    -- if the key does not exist
    IF @keyName IS NULL
    BEGIN
        DECLARE @clustered nvarchar(12)
        SET @clustered = 'CLUSTERED'

        -- if a clustered index already exists, make this one non-clustered
        IF EXISTS (SELECT 1 FROM sysindexes where id = OBJECT_ID(@tablename) AND indid = 1)
            SET @clustered = 'NONCLUSTERED'

        -- add the key
        EXEC ('ALTER TABLE ' + @tablename + ' ADD CONSTRAINT PK_' + @tablename + ' PRIMARY KEY ' + @clustered +' (' + @columns + ')')
    END
END

GO
Uses